﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Principal;

namespace XCommunity.Users
{


  /// <summary>
  /// 定义一个权限
  /// </summary>
  public interface IPermission
  {
    ControlType GetControl( string verb, params object[] frameObjects );
  }


  /// <summary>
  /// IPermission的标准实现
  /// </summary>
  public abstract class Permission : IPermission
  {

    public Permission( IUserService service )
    {
      Service = service;
    }


    /// <summary>
    /// 用户服务
    /// </summary>
    public IUserService Service
    {
      get;
      private set;
    }


    /// <summary>
    /// 获取某一个操作的权限控制
    /// </summary>
    /// <param name="verb"></param>
    /// <param name="frameObjects"></param>
    /// <returns></returns>
    public virtual ControlType GetControl( string verb, params object[] frameObjects )
    {
      var user = Service.GetUser();
      var controls = from item in GetControlItems() where item.IsSatisfied( user, verb, frameObjects ) select item.ControlType;

      return ComputeControl( controls );
    }



    /// <summary>
    /// 计算某一个操作的权限控制级别
    /// </summary>
    /// <param name="controls">权限控制级别项列表</param>
    /// <returns></returns>
    protected ControlType ComputeControl( IEnumerable<ControlItemType> controls )
    {

      bool allow = false;
      bool deny = false;
      bool request = false;

      foreach ( var item in controls )
      {
        if ( item == ControlItemType.Allow )
          allow = true;
        else if ( item == ControlItemType.Deny )
          deny = true;
        else if ( item == ControlItemType.Request )
          request = true;
        else if ( item == ControlItemType.DenyRequest )
          return ControlType.Deny;//如果存在一个DenyRequest权限控制符，则否定所有的其他权限。
        else
          throw new InvalidOperationException();//UNDONE 异常详细信息
      }

      if ( allow && !deny )
        return ControlType.Allow;  //如果具备允许权限但没有被阻止，则操作被允许
      else if ( request )
        return ControlType.Request;//否则如果有请求操作的权限，则可以请求操作
      else
        return ControlType.Deny;   //否则被阻止
    }


    protected virtual IEnumerable<IControlItem> GetControlItems()
    {
      return Enumerable.Empty<IControlItem>();
    }

  }
}
